<?php

namespace Pw\MainBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Pw\MainBundle\Entity\Guide;
use Pw\MainBundle\Form\Type\GuideType;
class GuideController extends Controller
{
    public function indexAction(){
		$em = $this->getDoctrine()->getManager();
		$guides = $em->getRepository('PwMainBundle:Guide')->getVisible();
		return $this->render('PwMainBundle:Guide:index.html.php',  array('guides' => $guides));
    }
	public function addAction(){
		if ($this->get('security.context')->isGranted('ROLE_USER')) {
			$guide = new Guide();
			$form = $this->createForm(new GuideType(), $guide);
			$request = $this->getRequest();
			if ($request->isMethod('POST')) {
			$form->bind($request);
				if ($form->isValid()) {
					$em = $this->getDoctrine()->getManager();
					$em->persist($guide);
					$em->flush();
					var_dump($guide->getId());
					//return $this->redirect($this->generateUrl('guide_edit', array('guideId' => $guide->getId())));
				}
			}
			return $this->render('PwMainBundle:Guide:add.html.php',  array('form' => $form->createView()));
		}
		return $this->render('PwMainBundle::auth.html.php');
	}

	public function editAction($guideId){
		$em = $this->getDoctrine()->getEntityManager();
		$guide = $em->getRepository('PwMainBundle:Guide')->find($guideId);
		if ($guide) {
			$form = $this->createForm(new GuideType(), $guide);
			$request = $this->getRequest();		
			if ($request->isMethod('POST')) {
				//save original chapters for later use
				$origChapters = array();
				foreach ($guide->getChapters() as $chapter) {
					$origChapters[] = $chapter;
				}				
				$form->bind($request);
				if ($form->isValid()) {
					
					//choose chapters for remove
					foreach ($origChapters as $key => $origChapter) {				
						foreach ($guide->getChapters() as $chapter) {
							if ($origChapter->getId() === $chapter->getId()) {
								unset($origChapters[$key]);
								break;
							}
						}
					}
					var_dump($guide->getChapters()->count());
//					foreach ($origChapters as $origChapter) {						
//						$em->remove($origChapter);
//					}
					$em->persist($guide);
					$em->flush();
					//return $this->redirect($this->generateUrl('guides_show'));
				}
			}
			return $this->render('PwMainBundle:Guide:edit.html.php',  array('form' => $form->createView(), 'guideId' => $guideId));
		}
		throw $this->createNotFoundException();
	}
	public function deleteAction($talentId){
		$em = $this->getDoctrine()->getEntityManager();
		$talent = $em->getRepository('PwMainBundle:Talent')->find($talentId);
		if ($talent) {
			$em->remove($talent);
			$em->flush();
		}
		return $this->redirect($this->generateUrl('talents_show'));
	}
	public function getJsonAction($talentId){
		$em = $this->getDoctrine()->getEntityManager();
		$talent = $em->getRepository('PwMainBundle:Talent')->find($talentId);
		$result = array();
		if ($talent) {
			$result = $talent->getArray4JSON();
		}
		return new JsonResponse($result);
	}
}
